﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;

namespace Virgee.Common.Services.Tests.Support
{
    public class TestApi2Controller : ApiController
    {
        public async Task<HttpResponseMessage> Post()
        {
            // Is somebody trying to post something else other than multipart content?
            if (!Request.Content.IsMimeMultipartContent())
            {
                // If so, then let them know.                
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            // Save files in temp folder.
            string root = System.IO.Path.GetTempPath();
            var provider = new MultipartFormDataStreamProvider(root);

            try
            {
                // Read the form data.
                await Request.Content.ReadAsMultipartAsync(provider);

                foreach (MultipartFileData file in provider.FileData)
                {
                    try
                    {
                        System.IO.File.Delete(file.LocalFileName);
                    }
                    catch { }
                }

                // Create the response.
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);

                return response;
            }
            catch (HttpResponseException)
            {
                // Re throw exceptions of this type.
                throw;
            }
            catch (Exception e)
            {
                // Something went wrong :(
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
        }
    }
}
